<?php
/**
 * Obtenemos los items de un menu que podemos ver.
 *
 * Estos se filtran por
 *
 * #auth si esta logueado
 * #secure si tiene permisos para un recurso en particular
 * #type El tipo de menu. 
 */
class Exts_Views_Helpers_Menu extends Zend_View_Helper_Abstract
{
    private $_session;

    public function menu()
    {
		$this->_session = new Zend_Session_Namespace('exts');
	    return $this;
    }

	public function get( $type = '' )
	{
		$menu = new Exts_Models_Menu();

		$where = "locked='F'";
		$where .= !empty( $type ) ?  " AND type='{$type}'" : '';
		
		$items = $menu->fetchAll( $where );
		$res = array();
		foreach( $items as $item ) {
			if( $item['auth'] == 'T' ) {
				if( ! $this->_hasIdentity() ) {
					continue;
				}
				if( $item['secure'] == 'T' ) {
					if( ! $this->_hasPermission(
							$item['module'], $item['controller'], $item['action']
					)){
						continue;
					}
				}
			}
			$res[] = $item->toArray();
		}
		return $res;

	}

	private function _hasIdentity()
	{
		return $this->_session->user->auth;
	}

	private function _hasPermission( $module, $controller, $action)
	{

        $user = $this->_session->user ;

		if( !is_array( $user->resources )) {
           return false;
        }
		
        if( !in_array( $controller, $user->resources  )) {
            return false;
        }

        $valid = $user->acl->isAllowed(
            $user->role, $controller, $action
        );

        if( !$valid ) {
            return false;
        }
		return true;
	}
	
}
